from django.db import transaction
from rest_framework import viewsets, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from task.models import Task, TaskUser
from teacher.serializer import TeacherSerializer
from djangoStudy.db import DBUtils

from django.db.models import Q, F
from djangoStudy.tool import teacher_build_query

import datetime
class GroupViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TeacherSerializer
    permission_classes = (permissions.AllowAny,)

    @action(methods=['GET'], detail=False)
    def get_group(self, request, *args, **kwargs):
        sql = """
        SELECT 
            g.id,
            g.create_time,
            COUNT(gu.user_id) as num,
            g.name
        FROM 
            tb_group g
        LEFT JOIN 
            tb_group_user gu ON g.id = gu.group_id
        WHERE 
            g.is_delete = 0 OR g.is_delete IS NULL
        GROUP BY 
            g.id
        ORDER BY 
            g.id;
        """
        results = DBUtils.select_all(sql,)
        # print(results)
        data_list = []
        for row in results:
            # 复制原始字典，避免修改原始数据
            processed_row = row.copy()
            # 处理日期格式
            if 'create_time' in processed_row and isinstance(processed_row['create_time'], datetime.datetime):
                processed_row['create_time'] = processed_row['create_time'].strftime('%Y-%m-%d %H:%M:%S')
            data_list.append(processed_row)
        # print(data_list)
        return Response(data={'data': data_list}, status=200)

    @action(methods=['POST'], detail=False)
    def get_assigned_group(self, request, *args, **kwargs):
        print(request.data)
        group_id = request.data['group_id']
        sql = """
                select 
                    user_id as id
                FROM tb_group_user
                where group_id = %s
                """
        data = DBUtils.select_all(sql, (group_id,))

        return Response(data={'data': data}, status=200)

    @action(detail=False, methods=['POST'])
    def assignGroupUser(self, request, *args, **kwargs):
        """ 分配数据 """
        user_ids = request.data['userIds']
        group_id = request.data['group_id']
        sql = """
                insert into tb_group_user (group_id, user_id)
                values (%s, %s)
            """
        for user_id in user_ids:
            DBUtils.insert(sql, args=(group_id, user_id,))
        return Response(data={'message': "分配成功"}, status=200)

    @action(detail=False, methods=['POST'])
    def deleteGroupUser(self, request, *args, **kwargs):
        """ 删除任务 """
        user_ids = request.data['userIds']
        group_id = request.data['group_id']
        sql = """
                    delete from tb_group_user where group_id = %s and user_id = %s
                """
        for user_id in user_ids:
            DBUtils.delete(sql, args=(group_id, user_id,))
        return Response(data={'message': "分配成功"}, status=200)

    @action(detail=False, methods=['POST'])
    def updateGroupName(self, request, *args, **kwargs):
        """ 修改任务名称 """
        group_id = request.data['group_id']
        name = request.data['name']
        # print(name)
        # print(group_id)

        sql = """
            update tb_group set name = %s where id = %s
        """

        DBUtils.update(sql, (name, group_id))

        return Response(status=200)

    @action(detail=False, methods=['POST'])
    def deleteGroup(self, request, *args, **kwargs):
        group_id = request.data['group_id']

        sql = """
        update tb_group set is_delete = 1, delete_time = now() where id = %s
        """
        DBUtils.update(sql, (group_id,))

        return Response(status=200)

    @action(detail=False, methods=['POST'])
    def addGroup(self, request, *args, **kwargs):

        name = request.data['name']

        sql = """
            insert into tb_group (name, create_time) values (%s, now())
        """
        DBUtils.insert(sql, (name,))
        return Response(status=200)

    @action(detail=False, methods=['POST'])
    def assignTasksToGroup(self, request, *args, **kwargs):
        task_ids = request.data['task_ids']
        user_ids = request.data['user_ids']
        print(user_ids, task_ids)

        # 使用事务提高性能
        with transaction.atomic():
            # 先获取所有已存在的任务-用户关联
            existing_links = set(
                TaskUser.objects.filter(
                    task_id__in=task_ids,
                    user_id__in=user_ids
                ).values_list('task_id', 'user_id')
            )

            # 准备要插入的数据
            new_links = []
            for user_id in user_ids:
                for task_id in task_ids:
                    # 检查这个组合是否已存在
                    if (task_id, user_id) not in existing_links:
                        new_links.append(
                            TaskUser(task_id=task_id, user_id=user_id, is_check=0, is_solve=0, status=0)
                        )

            # 批量创建新记录
            if new_links:
                TaskUser.objects.bulk_create(new_links)

        return Response(status=200)

    @action(detail=False, methods=['POST'])
    def selectAllUserTask(self, request, *args, **kwargs):
        group_id = request.data['group_id']
        """获取每个组的人员的所有的相同任务ID """
        sql ="""
            SELECT 
                tu.task_id as id
            FROM 
                tb_group g
            JOIN 
                tb_group_user gu ON g.id = gu.group_id
            JOIN 
                tb_task_user tu ON gu.user_id = tu.user_id
            where g.id = %s
            GROUP BY 
                g.id, tu.task_id
            HAVING 
                COUNT(DISTINCT gu.user_id) = (
                    -- 子查询获取该组的总人数
                    SELECT COUNT(*) 
                    FROM tb_group_user 
                    WHERE group_id = g.id
                )
            ORDER BY 
                g.id, tu.task_id;
        """

        data = DBUtils.select_all(sql, (group_id,))

        num = []

        for row in data:
            num.append(row['id'])
        return Response(data={'data': num}, status=200)
